package org.fyp.synchrona.services;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.util.EntityUtils;
import org.apache.http.impl.client.AbstractHttpClient;
import org.fyp.synchrona.core.info.impl.CommonDataObject;

public class MoodleProfiler implements Runnable {
	
	private CommonDataObject cpo;
	
	public MoodleProfiler(){
		
	}
	
	public void UpdateMoodle(){
		
	}

	@Override
	public void run() {
		String session = null;

        DefaultHttpClient httpclient = new DefaultHttpClient();

        HttpPost httpost = new HttpPost("http://localhost/moodle/login/index.php");

        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("username", "admin"));
        nvps.add(new BasicNameValuePair("password", "123"));

        try {
			httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

        HttpResponse response = null;
		try {
			response = httpclient.execute(httpost);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        HttpEntity entity = response.getEntity();
        

        System.out.println("Login form post: " + response.getStatusLine());
        if (entity != null) {
        	//System.out.println("Logged in page: "+EntityUtils.toString(entity));
            try {
				entity.consumeContent();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }

        
        HttpGet httpget = new HttpGet("http://localhost/moodle/user/editadvanced.php");
        try {
			response = httpclient.execute(httpget);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        entity = response.getEntity();
        String sesskey ="";

        System.out.println("Profile get: " + response.getStatusLine());
        if (entity != null) {
        	//System.out.println("Logged in page: "+EntityUtils.toString(entity));
        	String editPage = null;
			try {
				editPage = EntityUtils.toString(entity);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	//System.out.println(editPage);
         	String[] array = editPage.split("=\"sesskey\"");
         	//String array1[] = new String[100];
         	//System.out.println("this is array 1 ::"+array[1]);
         	array = array[1].split("value=\"");
         	
         	//System.out.println("printing array zero"+array[1]);
         	
         	sesskey = array[1].substring(0,(array[1].indexOf('\"')));
         	System.out.println(sesskey);
         	System.out.println(sesskey);
            try {
				entity.consumeContent();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        
        //update profile       
        HttpPost profileEdit   = new HttpPost("http://localhost/moodle/user/editadvanced.php");
        MultipartEntity reqEntity = new MultipartEntity();

        try {
			reqEntity.addPart("MAX_FILE_SIZE", new StringBody("16777216"));
			 reqEntity.addPart("id", new StringBody("2") );
		        reqEntity.addPart("course", new StringBody("1"));
		        reqEntity.addPart("mform_showadvanced_last", new StringBody("") );
		        reqEntity.addPart("sesskey", new StringBody(sesskey) ); //get session key
		        reqEntity.addPart("_qf__user_editadvanced_form", new StringBody("1") );
		        //reqEntity.addPart("mform_showadvanced", new StringBody("Show Advanced") );
		        reqEntity.addPart("username", new StringBody("admin"));
		        reqEntity.addPart("firstname", new StringBody("Hello") );
		        reqEntity.addPart("lastname", new StringBody("World"));
		  
		        	reqEntity.addPart("email", new StringBody("harini.sirisena@gmail.com") );
		       
		        reqEntity.addPart("maildisplay", new StringBody("1") );
		        reqEntity.addPart("emailstop", new StringBody("1") );
		        reqEntity.addPart("mailformat", new StringBody("1") );
		        reqEntity.addPart("maildigest", new StringBody("1") );
		        reqEntity.addPart("autosubscribe", new StringBody("1") );
		        reqEntity.addPart("trackforums", new StringBody("0") );
		        reqEntity.addPart("htmleditor", new StringBody("0") );
		        reqEntity.addPart("ajax", new StringBody("0") );
		        reqEntity.addPart("screenreader", new StringBody("1") );
		       // if(cpo.getCOUNTRY_CITY()!=null){
		        //	reqEntity.addPart("city", new StringBody(cpo.getCOUNTRY_CITY()) );
		       // }else{
		        	reqEntity.addPart("city", new StringBody("Moratuwa") );
		      //  }
		        
		        reqEntity.addPart("country", new StringBody("LK"));
		        reqEntity.addPart("timezone", new StringBody("5.5") );
		        if(cpo.getBIO()!=null){
		        	reqEntity.addPart("description", new StringBody(cpo.getBIO()) );
		        }
		        
		        reqEntity.addPart("lang", new StringBody("en_utf8") );
		        reqEntity.addPart("interests", new StringBody("") );
		        reqEntity.addPart("imagealt", new StringBody(""));
		        reqEntity.addPart("mform_showadvanced", new StringBody("") );
		        reqEntity.addPart("url", new StringBody(""));
		        reqEntity.addPart("icq", new StringBody("") );
		        reqEntity.addPart("skype", new StringBody("") );
		        reqEntity.addPart("aim", new StringBody("") );
		        reqEntity.addPart("yahoo", new StringBody("") );
		        reqEntity.addPart("msn", new StringBody(""));
		        reqEntity.addPart("idnumber", new StringBody("") );
		        reqEntity.addPart("institution", new StringBody("") );
		        reqEntity.addPart("department", new StringBody("") );
		        //if(cpo.getHOME_PHONE()!=null){
		        //	reqEntity.addPart("phone1", new StringBody(cpo.getHOME_PHONE()) );
		       // }else{
		        	reqEntity.addPart("phone1", new StringBody("") );
		       // }
		        
		        reqEntity.addPart("phone2", new StringBody("") );
		        reqEntity.addPart("address", new StringBody("") );
		        reqEntity.addPart("submitbutton", new StringBody("Update profile") );    
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       


        profileEdit.setEntity(reqEntity);
        try {
			response = httpclient.execute(profileEdit);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        entity = response.getEntity();
        System.out.println("Profile update: " + response.getStatusLine());
        if (entity != null) {
        	//System.out.println("Profile edit page: "+EntityUtils.toString(entity));
            try {
				entity.consumeContent();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }

        // When HttpClient instance is no longer needed, 
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();    
               
 		
		
	}

	public void setCpo(CommonDataObject cpo) {
		this.cpo = cpo;
	}

	public CommonDataObject getCpo() {
		return cpo;
	}

}
